import conf
from db import pg,namedata
from util import unixtime as epoch
from log import logging
import usermn as User, piece as Piece

def create(userId):
  pg.cursor.execute("INSERT INTO tables(player1_id,player1_epoch) VALUES(%(userId)i,%(epoch)i)"%{ 'userId':userId, 'epoch':epoch() })
  pg.connection.commit()
  pg.cursor.execute("SELECT CURRVAL('tables_id_seq')")
  tableId = pg.cursor.fetchone()[0]
  
  pg.cursor.execute("select create_%s_set(%i,%i)"%(
      conf.DEBUG and "debug" or "default",
      tableId, epoch()
    )
  )
  
  pg.connection.commit()
  return tableId, Piece.getByTableId(tableId)
  
def getAvailableTables():
  logging.info("Getting available games..")
  pg.cursor.execute('SELECT t.id,t.player1_epoch,u.name,u.location FROM tables t, users u WHERE t.player1_epoch>%i AND t.player2_id IS NULL AND t.player1_id = u.id'%(epoch()-conf.CHESS_SERVER["timeout"])) 
  result = namedata(pg.cursor.fetchall(),("table_id","table_last_move_epoch","user_name","user_location"))
  return result

def getOpponent(tableId):
  pg.cursor.execute('SELECT u.name,u.location,u.games_played,u.games_won FROM tables t, users u WHERE t.id = %i AND t.player2_id = u.id'%tableId)
  opponent = pg.cursor.fetchone()
  if opponent: opponent = namedata.single(opponent,("name","location","games_played","games_won"))
  return opponent

def getPlayers(tableId):
  pg.cursor.execute('SELECT player1_id, player2_id FROM tables WHERE id = %i'%tableId)
  result = pg.cursor.fetchall()
  return [ result[0][0], result[0][1] ]

def join(tableId,userId):
  pg.cursor.execute("UPDATE tables SET player2_id=%i, player2_epoch=%i WHERE id = %i"%(userId,epoch(),tableId))
  pg.connection.commit()
  
  return Piece.getByTableId(tableId), User.getById(getPlayers(tableId)[0]) # piece set, opponent profile

def update(tableId,color):
  pg.cursor.execute("UPDATE tables SET player%i_epoch = %i WHERE id = %i"%(color+1,epoch(),tableId))
  pg.connection.commit()
  
